<?php
/* Include session.inc, to allow database connection, and access to
 miscfunctions, and datefunctions.*/
$_SESSION['db'] = $db;
include 'api_errorcodes.php';
/* Include SQL_CommonFunctions.inc, to use GetNextTransNo().*/
include ($PathPrefix . 'includes/SQL_CommonFunctions.inc');

/* Get weberp authentication, and return a valid database
 connection */
function db($user, $password) {
    $_SESSION['UserID'] = $user;
    $sql = "SELECT fullaccess
				FROM www_users
				WHERE userid='" . DB_escape_string($user) . "'
				AND (password='" . CryptPass(DB_escape_string($password)) . "'
				OR  password='" . DB_escape_string($password) . "')";
    $Auth_Result = DB_query($sql, $_SESSION['db']);
    $myrow = DB_fetch_array($Auth_Result, SQLSRV_FETCH_ASSOC);
    if (DB_has_rows($Auth_Result) > 0) {
        $_SESSION['AccessLevel'] = $myrow['fullaccess'];
        $sql = 'SELECT tokenid FROM securitygroups
					WHERE secroleid =  ' . $_SESSION['AccessLevel'];
        $Sec_Result = DB_query($sql, $_SESSION['db']);

        $_SESSION['AllowedPageSecurityTokens'] = array();
        if (DB_has_rows($Sec_Result) == 0) {
            return NoAuthorisation;
        } else {
            $i = 0;
            while ($myrow = DB_fetch_array($Sec_Result)) {
                $_SESSION['AllowedPageSecurityTokens'][$i] = $myrow['tokenid'];
                $i++;
            }
        }
        return $_SESSION['db'];
    } else {
        return NoAuthorisation;
    }
}

/**
 * include all api
 */
include 'api_excel.php';
include 'api_ajax.php';
include 'api_song.php';
include 'api_company.php';
include 'api_object.php';
include 'api_securityroles.php';
include 'api_user.php';
include 'api_securitygroups.php';
include 'api_securitytokens.php';
include 'api_partner.php';
include 'api_partner_prices.php';
include 'api_album.php';
include 'api_type.php';
include 'api_exchange.php';
include 'api_contract.php';
include 'api_song_notlist.php';

/**
 * Return class name by shortname
 * @author trungpm
 * @static
 * @param string $name
 * @param string $type
 * @return string
 */
function _getClass($name, $type = 'model') {
    if (false === strpos($name, '/')) {
        return $name;
    }

    list($module, $class) = explode('/', $name);
    $class = str_replace(' ', '_', ucwords(str_replace('_', ' ', $class)));

    return 'Api_' . ucfirst($type) . '_' . $class;
}

/**
 * Returns singleton object
 * @author trungpm
 * @static
 * @param string $class
 * @param array $arguments [optional]
 */
function _single($class, $arguments = array()) {
    $class = _getClass($class);

    $instance = new $class($arguments);
    return $instance;
}

function _N($UnConvertString = '') {
    return iconv("UCS-2LE", "UTF-8", $UnConvertString);
}

function _convertHexToUCS2($UnConvertString) {
    return iconv("UCS-2LE", "UTF-8", $UnConvertString);
}

function _convertUCS2ToHex($value) {
    // sending data to database
    $ucs2 = iconv('UTF-8', 'UCS-2LE', $value);

    // converting UCS-2 string into "binary" hexadecimal form
    $arr = unpack('H*hex', $ucs2);
    $hex = "0x{$arr['hex']}";
    return $hex;
}

function excel_date($serial, $date_format) {

    // Excel/Lotus 123 have a bug with 29-02-1900. 1900 is not a
    // leap year, but Excel/Lotus 123 think it is...
    if ($serial == 60) {
        $day = 29;
        $month = 2;
        $year = 1900;

        //return sprintf('%02d/%02d/%04d', $month, $day, $year);
        return $this -> _format_date($month, $day, $year, $date_format);
    } else if ($serial < 60) {
        // Because of the 29-02-1900 bug, any serial date
        // under 60 is one off... Compensate.
        $serial++;
    }

    // Modified Julian to DMY calculation with an addition of 2415019
    $l = $serial + 68569 + 2415019;
    $n = floor((4 * $l) / 146097);
    $l = $l - floor((146097 * $n + 3) / 4);
    $i = floor((4000 * ($l + 1)) / 1461001);
    $l = $l - floor((1461 * $i) / 4) + 31;
    $j = floor((80 * $l) / 2447);
    $day = $l - floor((2447 * $j) / 80);
    $l = floor($j / 11);
    $month = $j + 2 - (12 * $l);
    $year = 100 * ($n - 49) + $i + $l;
    //return sprintf('%02d/%02d/%04d', $month, $day, $year);
    return _format_date($month, $day, $year, $date_format);
}

//Return value in format
function _format_date($month, $day, $year, $format) {
    $separator = stripos($format, '-') > 0 ? '-' : '/';
    $arr_format = preg_split('/-|\//', $format);
    //switch key and value [0 => 'Y', 1 => 'm', 2=> 'd'] --> ['Y' => 0, 'm' => 1, 'd' => 2]
    $arr_format = array_flip($arr_format);
    //change key to lower case
    $arr_format = array_change_key_case($arr_format, CASE_LOWER);
    $arr_format['y'] = $year;
    $arr_format['m'] = $month;
    $arr_format['d'] = $day;
    $ret_val = '';
    foreach ($arr_format as $key => $value) {
        //Adding pad for day or month. ex; 8 --> 08
        $ret_val .= str_pad($value, 2, '0', STR_PAD_LEFT) . $separator;
    }
    //Cut last separetor
    if (strlen($ret_val) > 1)
        $ret_val = substr($ret_val, 0, strlen($ret_val) - 1);
    return $ret_val;
}
?>
